#include "logicfight.h"
#include"networkmanager.h"
#include"messageconst.h"
#include<iostream>

using namespace std;

DEFINE_SINGLE_ATTRIBUTES(LogicFight);

LogicFight::LogicFight()
{
    NET_INSTANCE()->add(MESSAGE_PLAYER_ATTACK,handler(this,SEL_EVENTFUNC(LogicFight::c2sPlayerAtk)));
    NET_INSTANCE()->add(MESSAGE_MONSTER_ATTACK,handler(this,SEL_EVENTFUNC(LogicFight::c2sMonsterAtk)));
    NET_INSTANCE()->add(MESSAGE_PLAYER_RUN,handler(this,SEL_EVENTFUNC(LogicFight::c2sPlayerRun)));
    NET_INSTANCE()->add(MESSAGE_USE_MEDICATION,handler(this,SEL_EVENTFUNC(LogicFight::c2sUseMedication)));
    NET_INSTANCE()->add(MESSAGE_PLAYER_DIE,handler(this,SEL_EVENTFUNC(LogicFight::c2sPlayerDie)));
}

void LogicFight::c2sPlayerAtk(Json::Value& msg)
{
    cout<<"ogicFight::c2sPlayerAtk"<<msg.toStyledString()<<endl;
    int fd=NET_INSTANCE()->getFd();
    auto& playermaps=NET_SOCKET().m_playermaps;
    msg["fd"]=fd;
    int dest=msg["dest"].asInt();
    if(playermaps.find(dest)!=playermaps.end())
    {
        cout<<playermaps[fd].rolename<<" attack monster"<<endl;
        NET_INSTANCE()->send(dest,MESSAGE_PLAYER_ATTACK,msg);
        //SendMsg(msg->dest,(char*)msg,sizeof(PlayerAtk_Msg));
    }
}

void LogicFight::c2sMonsterAtk(Json::Value& msg)
{
    int fd=NET_INSTANCE()->getFd();
    auto& playermaps=NET_SOCKET().m_playermaps;
    msg["fd"]=fd;
    int dest=msg["dest"].asInt();
    if(playermaps.find(dest)!=playermaps.end())
    {
        cout<<"monster attack "<<playermaps[dest].rolename<<endl;
        NET_INSTANCE()->send(dest,MESSAGE_MONSTER_ATTACK,msg);
        //SendMsg(msg->dest,(char*)msg,sizeof(MonsterAtk_Msg));
    }
}

void LogicFight::c2sPlayerRun(Json::Value& msg)
{
    int fd=NET_INSTANCE()->getFd();
    auto& playermaps=NET_SOCKET().m_playermaps;
    msg["fd"]=fd;
    int dest=msg["dest"].asInt();
    if(playermaps.find(dest)!=playermaps.end())
    {
        cout<<playermaps[fd].rolename<<" run away"<<endl;
        NET_INSTANCE()->send(dest,MESSAGE_PLAYER_RUN,msg);
        //SendMsg(msg->dest,(char*)msg,sizeof(PlayerRun_Msg));
    }
}

void LogicFight::c2sUseMedication(Json::Value& msg)
{
    int fd=NET_INSTANCE()->getFd();
    auto& playermaps=NET_SOCKET().m_playermaps;
    msg["fd"]=fd;
    int dest=msg["dest"].asInt();
    if(playermaps.find(dest)!=playermaps.end())
    {
        cout<<playermaps[fd].rolename<<" use medication"<<endl;
        NET_INSTANCE()->send(dest,MESSAGE_PLAYER_RUN,msg);
        //SendMsg(msg->dest,(char*)msg,sizeof(PlayerRun_Msg));
    }
}

void LogicFight::c2sPlayerDie(Json::Value& msg)
{
    int fd=NET_INSTANCE()->getFd();
    auto& playermaps=NET_SOCKET().m_playermaps;
    msg["fd"]=fd;
    int dest=msg["dest"].asInt();
    if(playermaps.find(dest)!=playermaps.end())
    {
        cout<<playermaps[fd].rolename<<" die!"<<endl;
        NET_INSTANCE()->send(dest,MESSAGE_PLAYER_RUN,msg);
        //SendMsg(msg->dest,(char*)msg,sizeof(PlayerRun_Msg));
    }
}
